﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Huish
{
    public partial class amortize : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnCalculate_Click1(object sender, EventArgs e)
        {
            // the formulas are found in  http://en.wikipedia.org/wiki/Amortization_calculator

            double monthlyInterest = (double.Parse(dfnAnnualRate.Text) / 100) / double.Parse(dfnPaymentsPerYear.Text); // assuming no compunding


            double numerator = monthlyInterest * (Math.Pow((1 + monthlyInterest), double.Parse(dfnTotalPayments.Text))) * double.Parse(dfnPrinciple.Text);
            double denumerator = (Math.Pow((1 + monthlyInterest), double.Parse(dfnTotalPayments.Text))) - 1;

            double monthlyPayment = numerator / denumerator;

            List<Payment> Schedule = new List<Payment>();
            Payment InitialRecord = new Payment();
            InitialRecord.Balance = double.Parse(dfnPrinciple.Text);
            Schedule.Add(InitialRecord);
            for (int i = 1; i <= int.Parse(dfnTotalPayments.Text); i++)
            {
                Payment p = new Payment();
                p.Seq = i;
                p.MonthlyPayment = Math.Round(monthlyPayment, 2);
                p.InterestPayment = Math.Round(monthlyInterest * Schedule[i - 1].Balance, 2);
                p.PrinciplePayment = Math.Round(p.MonthlyPayment - p.InterestPayment, 2);
                p.Balance = Math.Round(Schedule[i - 1].Balance - p.PrinciplePayment, 2);
                Schedule.Add(p);


            }

            //adjust the last payment
            Schedule[Schedule.Count - 1].PrinciplePayment = Schedule[Schedule.Count - 2].Balance;
            Schedule[Schedule.Count - 1].Balance = 0;
            Schedule[Schedule.Count - 1].MonthlyPayment = Schedule[Schedule.Count - 1].PrinciplePayment + Schedule[Schedule.Count - 1].InterestPayment;

            grdSchedule.DataSource = Schedule;
            grdSchedule.DataBind();
        }
    }
}
